import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import index from '@/views/index'
import store from '@/store/index'
import axios from "../axios";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
        children: [
            {
                path: '/index',
                name: 'index',
                meta: {
                    title: '首页'
                },
                component: index
            },
            {
                path: '/userCenter',
                name: 'userCenter',
                meta: {
                    title: '个人中心'
                },
                component: () => import('@/views/UserCenter')
            },
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import( '../views/Login.vue')
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

//全局路由守卫
router.beforeEach((to, from, next) => {
    //取到状态的路由信息
    let hasRouter = store.getters.getRouterStatus
    //取到本地储存的token
    let token = localStorage.getItem('token')

    //如果当前是登录 直接放行
    if (to.path == '/login') {
        next()
    } else if (!token) {
        //如果没有token 那么去登录
        next({path: '/login'})
    } else if (!hasRouter) {
        //如果没有菜单信息 那么后台请求 获取菜单
        axios.get("/sys/menu/nav", {
            headers: {
                Authorization: localStorage.getItem('token')
            }
        }).then(res => {
            //拿到用户的菜单
            store.dispatch("setMenuList", res.data.data.nav)
            //拿到用户的权限
            store.dispatch("setPermList", res.data.data.authoritys)

            //动态绑定路由
            //拿到路由
            let newRoutes = router.options.routes
            console.log("newRoutes->",newRoutes)
            res.data.data.nav.forEach(menu => {
                if (menu.children) {
                    menu.children.forEach(e => {
                        //将菜单转为路由
                        let router = menuToRoute(e)
                        //把路由加到路由管理里面
                        if (router) {
                            newRoutes[0].children.push(router)
                        }
                    })
                }
            })

            console.log("路由", newRoutes)
            router.addRoutes(newRoutes)

            store.dispatch("changeRouterStatus", true)
        })
    }
    next()
})

//将菜单转为路由
const menuToRoute = (menu) => {
    if (!menu.component) {
        return null
    }

    let router = {
        name: menu.name,
        path: menu.path,
        component: () => import("@/views/" + menu.component),
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    }

    return router

}

export default router
